<template>
  <div class="section-container">
    <!-- 简化的操作栏 -->
    <div class="action-bar">
      <el-input v-model="keyword" placeholder="搜索访视名称" clearable @keyup.enter.native="onSearch" @clear="onSearch" style="width: 240px; margin-right: 8px;" />
      <el-button 
        type="primary" 
        @click="handleCreate" 
        :disabled="!currentProjectId"
        size="default"
      >
        添加访视
      </el-button>
    </div>
    
    <!-- 访视表格 -->
    <div class="table-wrapper">
      <el-table 
        :data="sections" 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="加载访视列表..."
        :height="'calc(100vh - 290px)'"
        stripe
      >
        <el-table-column prop="name" label="访视名称" min-width="120" />
        <el-table-column label="访视OID" min-width="220" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="text-muted">{{ row._id || row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="order" label="排序" width="80" align="center" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip min-width="150" />
        <el-table-column label="表单数" width="80" align="center">
          <template #default="{ row }">
            <el-tag size="small" type="info">{{ row.forms?.length || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            <span class="text-muted">{{ formatDate(row.createTime || row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button link type="primary" size="small" @click="handleFormConfig(row)">配置表单</el-button>
              <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-if="pagination"
          :current-page="pagination.page"
          :page-size="pagination.limit"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          small
        />
      </div>
    </div>

    <!-- 访视编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑访视' : '添加访视'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="访视OID" v-if="isEdit">
          <el-input :model-value="currentSection?._id || currentSection?.id" readonly />
        </el-form-item>
        <el-form-item label="访视名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入访视名称" />
        </el-form-item>
        <el-form-item label="排序号" prop="order">
          <el-input-number 
            v-model="formData.order" 
            :min="1" 
            :step="1"
            :readonly="!isEdit"
            placeholder="自动分配排序号"
            style="width: 100%"
          />
          <div v-if="!isEdit" class="order-tip">
            新增访视时系统将自动分配排序号
          </div>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="3"
            placeholder="请输入访视描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表单配置对话框 -->
    <el-dialog
      v-model="formConfigVisible"
      title="表单配置"
      width="800px"
    >
      <el-transfer
        v-model="selectedForms"
        :data="allForms"
        :titles="['可选表单', '已选表单']"
        :props="{
          key: '_id',
          label: 'name'
        }"
        v-loading="formsLoading"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formConfigVisible = false">取消</el-button>
          <el-button type="primary" @click="handleFormConfigSubmit" :loading="configSubmitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useSectionsStore } from '@/stores/sections'
import { useFormStore } from '@/stores/form'
import { useProjectStore } from '@/stores/project'
import { useRoute } from 'vue-router'

const sectionsStore = useSectionsStore()
const formStore = useFormStore()
const projectStore = useProjectStore()

const sections = ref([])
const projects = ref([])
const currentProjectId = ref('')
const pagination = ref(null)
const dialogVisible = ref(false)
const formConfigVisible = ref(false)
const isEdit = ref(false)
const currentSection = ref(null)
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)
const formsLoading = ref(false)
const configSubmitting = ref(false)
const keyword = ref('')

const queryParams = reactive({
  page: 1,
  limit: 10,
  sortBy: 'order',
  sortOrder: 'asc'
});

// 获取路由参数中的项目ID
const route = useRoute()

onMounted(() => {
  // 如果路由中有项目ID参数，则自动设置当前项目ID
  // 假设路由为 /projects/:projectId/manage
  const projectId = route.params.projectId
  if (projectId) {
    currentProjectId.value = projectId
    getSections()
  } else {
    // 如果没有参数，则获取项目列表
    getProjects()
  }
})

console.log('route', route)

// 表单数据
const formData = reactive({
  name: '',
  order: 1,
  description: ''
})

// 表单规则
const rules = {
  name: [
    { required: true, message: '请输入访视名称', trigger: 'blur' }
  ],
  order: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 表单配置相关
const allForms = ref([])
const selectedForms = ref([])

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取项目列表
const getProjects = async () => {
  try {
    const data = await projectStore.fetchProjects()
    projects.value = data
    // 如果只有一个项目，自动选择
    if (data.length === 1) {
      currentProjectId.value = data[0]._id || data[0].id
      await getSections()
    }
  } catch (error) {
    ElMessage.error('获取项目列表失败')
  }
}

// 获取章节列表
const getSections = async () => {
  if (!currentProjectId.value) return
  
  loading.value = true
  try {
    sectionsStore.setCurrentProjectId(currentProjectId.value)
    const response = await sectionsStore.fetchSections(currentProjectId.value, { ...queryParams, search: keyword.value?.trim() })
    sections.value = response.data
    pagination.value = response.pagination
    console.log('获取到的章节列表:', response.data)
  } catch (error) {
    ElMessage.error('获取章节列表失败')
    console.error('获取章节列表失败:', error)
  } finally {
    loading.value = false
  }
}

const onSearch = () => {
  queryParams.page = 1
  getSections()
}

const handleSizeChange = (size) => {
  queryParams.limit = size;
  getSections();
};

const handlePageChange = (page) => {
  queryParams.page = page;
  getSections();
};

// 处理项目变更
const handleProjectChange = () => {
  queryParams.page = 1;
  getSections()
}

// 获取所有表单（拉取足够多，避免分页遗漏导致无法关联/移除）
const getAllForms = async () => {
  formsLoading.value = true
  const projectId = route.params.projectId;
  let params = {
    projectId,
    page: 1,
    limit: 1000, // 拉大分页，确保拉全该项目下的表单
    sortBy: 'order',
    sortOrder: 'asc'
  }
  try {
    const data = await formStore.getAllForms(params)
    
    console.log('data', data)
    // 获取当前访视已选择的表单ID列表
    const selectedFormIds = currentSection.value?.forms?.map(f => f._id || f.id) || []
    
    allForms.value = data.data.map(form => ({
      ...form,
      _id: form._id || form.id,
      // 不禁用已选表单，允许移除
      disabled: false
    }))
  } catch (error) {
    ElMessage.error('获取表单列表失败')
  } finally {
    formsLoading.value = false
  }
}

// 创建章节
const handleCreate = () => {
  if (!currentProjectId.value) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  isEdit.value = false
  formData.name = ''
  formData.order = sections.value.length + 1
  formData.description = ''
  dialogVisible.value = true
}

// 编辑章节
const handleEdit = (row) => {
  isEdit.value = true
  currentSection.value = row
  Object.assign(formData, {
    name: row.name,
    order: row.order,
    description: row.description || ''
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (isEdit.value) {
          await sectionsStore.updateSection({
            ...currentSection.value,
            name: formData.name,
            order: formData.order,
            description: formData.description
          })
          ElMessage.success('更新成功')
        } else {
          await sectionsStore.createSection({
            name: formData.name,
            order: formData.order,
            description: formData.description
          }, currentProjectId.value)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        getSections()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
        console.error('操作失败:', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 表单配置
const handleFormConfig = async (row) => {
  currentSection.value = row
  await getAllForms()
  
  // 确保selectedForms只包含当前访视已选择的表单ID
  selectedForms.value = row.forms?.map(f => f._id || f.id) || []
  console.log('当前访视的表单:', row.forms)
  console.log('设置的selectedForms:', selectedForms.value)
  console.log('所有可选表单:', allForms.value.map(f => ({ id: f._id, name: f.name })))
  
  formConfigVisible.value = true
}

// 提交表单配置
const handleFormConfigSubmit = async () => {
  configSubmitting.value = true
  try {
    // 只传递表单ID数组给后端，而不是完整的表单对象
    const updateData = {
      ...currentSection.value,
      forms: selectedForms.value  // selectedForms.value 已经是ID数组
    }
    
    console.log('提交的数据:', updateData)
    console.log('selectedForms:', selectedForms.value)
    
    await sectionsStore.updateSection(updateData)
    ElMessage.success('配置成功')
    formConfigVisible.value = false
    getSections()
  } catch (error) {
    ElMessage.error('配置失败')
    console.error('表单配置失败:', error)
  } finally {
    configSubmitting.value = false
  }
}

// 删除章节
const handleDelete = (row) => {
  // 先检查是否有关联表单
  if (row.forms && row.forms.length > 0) {
    const formList = row.forms.map(form => `• ${form.name || (form._id || form.id)}`).join('\n');
    
    ElMessageBox.alert(
      `该章节下还有 ${row.forms.length} 个关联表单，请先删除以下表单后再删除章节：\n\n${formList}`, 
      '无法删除章节', 
      {
        confirmButtonText: '我知道了',
        type: 'warning'
      }
    );
    return;
  }

  // 如果没有关联表单，继续删除流程
  ElMessageBox.confirm('确认删除该章节吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await sectionsStore.deleteSection(row._id || row.id)
      ElMessage.success('删除成功')
      getSections()
    } catch (error) {
      if (error.response?.status === 400) {
        ElMessage.error(error.response.data.message || '删除失败：章节下还有关联表单')
      } else {
        ElMessage.error('删除失败')
      }
      console.error('删除失败:', error)
    }
  })
}

// 初始化
onMounted(() => {
  getProjects()
})

// 暴露方法给父组件调用
defineExpose({
  getSections
})
</script>

<style scoped>
.section-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 操作栏样式 */
.action-bar {
  position: absolute;
  top: -32px;
  right: 0;
}

/* 表格容器 */
.table-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-top: 10px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

:deep(.el-table__header) {
  background: #fafafa;
}

:deep(.el-table th) {
  background: #fafafa !important;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #e4e7ed;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background: #f8f9fa;
}

/* 操作按钮组 */
.action-buttons {
  display: flex;
  gap: 4px;
  align-items: center;
}

.action-buttons .el-button + .el-button {
  margin-left: 0;
}

/* 文本样式 */
.text-muted {
  color: #909399;
  font-size: 13px;
}

/* 分页容器 */
.pagination-wrapper {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.order-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 穿梭框样式优化 */
:deep(.el-transfer) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-transfer__buttons) {
  padding: 0 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    padding: 12px 0;
  }
  
  .table-wrapper {
    margin: 0 -8px;
  }
  
  :deep(.el-table) {
    border-radius: 0;
  }
  
  .pagination-wrapper {
    padding: 12px 8px;
  }
}

/* 美化滚动条 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style> 